package com.by_man.presenter.module_gestureLock;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.LoginActivity;
import com.by_man.presenter.R;
import com.by_man.repository.IpAddress;
import com.by_man.repository.PostStringRequest;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by man on 2017-03-17.
 */
public class GestureLockActivity extends AppCompatActivity {
    private RequestQueue rQueue;
    private GestureLockViewGroup mGestureLockViewGroup;
    private int[] password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gesture_lock);
        rQueue = Volley.newRequestQueue(this);
        rQueue.start();
        //页面相关组件的初始化
        initView();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode,event);
    }

    private void initView() {
        mGestureLockViewGroup = (GestureLockViewGroup) findViewById(R.id.id_gestureLockViewGroup);
        if (null == UserInfos.GestureLockAnswer) {
            // 从服务器拉取密码
            HashMap<String, String> params = new HashMap<>();
            params.put("token", UserInfos.token);
            PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST,
                    IpAddress.GestureLock, params,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            try {
                                JSONArray jsonArray = new JSONArray(s);
                                JSONObject temp = (JSONObject) jsonArray.get(0);
                                String gesture = temp.getString("gesture");
                                char[] c = gesture.toCharArray();
                                //String 转char[]型数组
                                String[] strArr = new String[c.length];
                                //char型数组转String型
                                for (int i = 0; i < c.length; i++) {
                                    strArr[i] = String.valueOf(c[i]);
                                }
                                //String型数组转int型数组
                                password = new int[strArr.length];
                                for (int i = 0; i < strArr.length; i++) {
                                    password[i] = Integer.parseInt(strArr[i]);
                                }
                            } catch (JSONException je) {
                                je.printStackTrace();
                            }
                            mGestureLockViewGroup.setAnswer(password);
                            mGestureLockViewGroup
                                    .setOnGestureLockViewListener(new GestureLockViewGroup.OnGestureLockViewListener()
                                                                  {
                                                                      /**
                                                                       * 错误超过五次控制
                                                                       */
                                                                      @Override
                                                                      public void onUnmatchedExceedBoundary() {
                                                                          Toast.makeText(GestureLockActivity.this, "错误3次,请您重新登录后修改手势密码",
                                                                                  Toast.LENGTH_SHORT).show();
                                                                          mGestureLockViewGroup.setUnMatchExceedBoundary(4);
                                                                          Intent intent = new Intent(GestureLockActivity.this, LoginActivity.class);
                                                                          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                                          startActivity(intent);
                                                                      }

                                                                      /**
                                                                       *判断手势对错，可在下面控制intent
                                                                       */
                                                                      @Override
                                                                      public void onGestureEvent(boolean matched) {
                                                                          //  Toast.makeText(PassWord.this, matched + "", Toast.LENGTH_SHORT).show();

                                                                          if (matched)   // 密码验证之后跳转
                                                                          {
                                                                              Toast.makeText(GestureLockActivity.this, "手势密码正确，即将为您跳转！" + "", Toast.LENGTH_SHORT).show();
                                                                              jumpActivity();

                                                                          } else {
                                                                              Toast.makeText(GestureLockActivity.this, "手势密码错误，请重新输入！" + "", Toast.LENGTH_SHORT).show();
                                                                              mGestureLockViewGroup.reset();

                                                                          }
                                                                      }

                                                                      @Override
                                                                      public void onBlockSelected(int[] c) {
                                                                      }
                                                                  }

                                    );
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e("GestureLockError",volleyError.getMessage(),volleyError);
                        }
                    });
            rQueue.add(stringRequest);
        } else {
            String gesture = UserInfos.GestureLockAnswer;
            char[] c = gesture.toCharArray();
            //String 转char[]型数组
            String[] strArr = new String[c.length];
            //char型数组转String型
            for (int i = 0; i < c.length; i++) {
                strArr[i] = String.valueOf(c[i]);
            }
            //String型数组转int型数组
            password = new int[strArr.length];
            for (int i = 0; i < strArr.length; i++) {
                password[i] = Integer.parseInt(strArr[i]);
            }

            mGestureLockViewGroup.setAnswer(password);
            mGestureLockViewGroup
                    .setOnGestureLockViewListener(new GestureLockViewGroup.OnGestureLockViewListener()
                                                  {
                                                      /**
                                                       * 错误超过五次控制
                                                       */
                                                      @Override
                                                      public void onUnmatchedExceedBoundary() {
                                                          Toast.makeText(GestureLockActivity.this, "错误3次,请您重新登录后修改手势密码",
                                                                  Toast.LENGTH_SHORT).show();
                                                          mGestureLockViewGroup.setUnMatchExceedBoundary(4);
                                                          Intent intent = new Intent(GestureLockActivity.this, LoginActivity.class);
                                                          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                          startActivity(intent);
                                                      }

                                                      /**
                                                       *判断手势对错，可在下面控制intent
                                                       */
                                                      @Override
                                                      public void onGestureEvent(boolean matched) {
                                                          //  Toast.makeText(PassWord.this, matched + "", Toast.LENGTH_SHORT).show();

                                                          if (matched)   // 密码验证之后跳转
                                                          {
                                                              Toast.makeText(GestureLockActivity.this, "手势密码正确，即将为您跳转！" + "", Toast.LENGTH_SHORT).show();
                                                              jumpActivity();

                                                          } else {
                                                              Toast.makeText(GestureLockActivity.this, "手势密码错误，请重新输入！" + "", Toast.LENGTH_SHORT).show();
                                                              mGestureLockViewGroup.reset();

                                                          }
                                                      }

                                                      @Override
                                                      public void onBlockSelected(int[] c) {
                                                      }
                                                  }

                    );
        }
    }

    private void jumpActivity() {
        String className = getIntent().getStringExtra("class");
        int position = getIntent().getIntExtra("position", 0);
        try {
            Intent intent = new Intent(this, Class.forName(className));
            intent.putExtra("position", position);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } catch (ClassNotFoundException ce) {
            ce.printStackTrace();
        }
    }
}
